<template>
  <div class="sale-contract-view" v-loading="loading">
    <el-card class="contract-detail-card" shadow="hover">
      <div v-if="contractDetail" class="contract-detail-content">
        <!-- 基本信息部分 -->
        <div class="info-section">
          <div class="section-header">
            <h3 class="section-title">基本信息</h3>
            <div class="contract-category-tag">
              {{ contractDetail.cate_title }}
            </div>
          </div>
          <el-descriptions :column="2" size="large" class="info-descriptions">
            <el-descriptions-item label="合同编号">{{ contractDetail.code }}</el-descriptions-item>
            <el-descriptions-item label="合同名称">{{ contractDetail.name }}</el-descriptions-item>
            <el-descriptions-item label="客户名称">
              {{ contractDetail.customer }}
            </el-descriptions-item>
            <el-descriptions-item label="签约主体">
              {{ contractDetail.subject_title }}
            </el-descriptions-item>
            <el-descriptions-item label="合同金额">
              {{ formatCurrencyWithoutSymbol(contractDetail.cost) }}元
            </el-descriptions-item>
            <el-descriptions-item label="到账金额">
              {{ formatCurrencyWithoutSymbol(contractDetail.cost2) }}元
            </el-descriptions-item>
            <el-descriptions-item label="后期费用" :span="2">
              {{ contractDetail.cost3 ? contractDetail.cost3 : '（无）' }}
            </el-descriptions-item>
            <el-descriptions-item label="签约日期">
              {{ formatDate(contractDetail.sign_time) }}
            </el-descriptions-item>
            <el-descriptions-item label="合同期限">
              {{ calculateDaysLeft(contractDetail.end_time) }}天
            </el-descriptions-item>
            <el-descriptions-item label="合同开始日期">
              {{ formatDate(contractDetail.start_time) }}
            </el-descriptions-item>
            <el-descriptions-item label="合同结束日期">
              {{ formatDate(contractDetail.end_time) }}
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">
              {{ contractDetail.remark ? contractDetail.remark : '（无）' }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDateTime(contractDetail.create_time) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ formatDateTime(contractDetail.update_time) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 签约信息部分 -->
        <div class="info-section">
          <h3 class="section-title">签约信息</h3>
          <el-descriptions :column="2" size="large" class="info-descriptions">
            <el-descriptions-item label="客户签约人">
              {{ contractDetail.contact_name || '（无）' }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ contractDetail.contact_mobile || '（无）' }}
            </el-descriptions-item>
            <el-descriptions-item label="联系地址" :span="2">
              {{ contractDetail.contact_address || '（无）' }}
            </el-descriptions-item>
            <el-descriptions-item label="签约销售">
              {{ contractDetail.sign_name || '（无）' }}
            </el-descriptions-item>
            <el-descriptions-item label="所属部门">
              {{ contractDetail.sign_department || '（无）' }}
            </el-descriptions-item>
            <el-descriptions-item label="录入人">
              {{ contractDetail.admin_name || '（无）' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 合同文档部分 -->
        <div class="info-section">
          <h3 class="section-title">合同文档</h3>
          <div class="document-list">
            <div
              v-if="!contractDetail.attachments || contractDetail.attachments.length === 0"
              class="empty-data"
            >
              <el-empty description="暂无合同文档" />
            </div>
            <div v-else class="attachment-list">
              <el-table
                :data="contractDetail.attachments"
                class="custom-table"
                border
                :max-height="'none'"
              >
                <el-table-column
                  prop="name"
                  label="文件名称"
                  min-width="200"
                  show-overflow-tooltip
                />
                <el-table-column prop="filesize" label="文件大小" width="120">
                  <template #default="scope">
                    {{ scope.row.filesize ? formatFileSize(scope.row.filesize) : '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="create_time" label="上传时间" width="180">
                  <template #default="scope">
                    {{ scope.row.create_time ? formatDateTime(scope.row.create_time) : '-' }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" align="center">
                  <template #default="scope">
                    <el-button type="primary" link size="small" @click="downloadFile(scope.row)">
                      下载
                    </el-button>
                    <el-button
                      v-if="isPreviewableFile(scope.row.fileext)"
                      type="success"
                      link
                      size="small"
                      @click="previewFile(scope.row)"
                    >
                      预览
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <!-- 操作日志部分 -->
        <div class="info-section">
          <h3 class="section-title">操作日志</h3>
          <div class="tab-content">
            <div v-if="logs.length === 0" class="empty-data">
              <el-empty description="暂无操作日志" />
            </div>
            <div v-else>
              <el-table :data="logs" class="custom-table" border>
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="content" label="操作内容" min-width="200" />
                <el-table-column prop="creator_name" label="操作人" width="120" />
                <el-table-column prop="ip" label="IP地址" width="150" />
                <el-table-column prop="create_time" label="操作时间" width="180">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.create_time) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="imagePreviewVisible"
      :title="previewImage.title"
      width="80%"
      top="50px"
      class="image-preview-dialog"
      append-to-body
    >
      <div class="image-preview-container">
        <el-image
          :src="previewImage.url"
          :preview-src-list="[previewImage.url]"
          fit="contain"
          class="preview-image"
        />
      </div>
    </el-dialog>

    <!-- 文档预览对话框 -->
    <el-dialog
      v-model="documentPreviewVisible"
      :title="previewDocument.title"
      width="98%"
      top="10px"
      class="document-preview-dialog"
      :fullscreen="isFullscreen"
      :destroy-on-close="true"
      append-to-body
    >
      <div class="document-preview-toolbar">
        <div class="toolbar-left">
          <el-button
            type="primary"
            :icon="isFullscreen ? 'CircleClose' : 'FullScreen'"
            size="small"
            @click="toggleFullscreen"
          >
            {{ isFullscreen ? '退出全屏' : '全屏查看' }}
          </el-button>
        </div>

        <div class="toolbar-right">
          <el-button type="primary" size="small" @click="openInNewTab(previewDocument.url)">
            在新窗口中打开
          </el-button>

          <!-- 备用预览选项 -->
          <template
            v-if="
              hasBackupPreviewOptions &&
              isOfficeFile(
                contractDetail.attachments.find(f => f.name === previewDocument.title)?.fileext ||
                  ''
              )
            "
          >
            <el-dropdown
              size="small"
              @command="
                (command: string) => {
                  const file = contractDetail.attachments.find(
                    f => f.name === previewDocument.title
                  )
                  if (!file) return

                  let fileUrl = file.filepath
                  fileUrl = fileUrl.replace(/\\/g, '/')
                  if (!fileUrl.startsWith('http://') && !fileUrl.startsWith('https://')) {
                    fileUrl = apiBaseUrl + fileUrl
                  }

                  if (command === 'office') {
                    previewWithOfficeOnline(fileUrl)
                  } else if (command === 'google') {
                    previewWithGoogleDocs(fileUrl)
                  } else if (command === 'download') {
                    directDownload(file)
                  }
                }
              "
            >
              <el-button size="small">
                切换预览方式
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="office">使用Office Online预览</el-dropdown-item>
                  <el-dropdown-item command="google">使用Google Docs预览</el-dropdown-item>
                  <el-dropdown-item command="download">下载后查看</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>

          <el-button type="default" size="small" @click="documentPreviewVisible = false">
            关闭
          </el-button>
        </div>
      </div>
      <div class="document-preview-container">
        <iframe
          v-if="documentPreviewVisible"
          :src="previewDocument.url"
          frameborder="0"
          class="document-preview-iframe"
          :class="{ 'pdf-preview': previewDocument.type === 'pdf' }"
        ></iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, defineProps, watch, onUnmounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { ArrowDown, FullScreen, CircleClose } from '@element-plus/icons-vue'
  import request from '@/utils/request'
  import { formatDate, formatDateTime, formatCurrency } from '@/utils/format'
  import { contractApi } from '@/api/contract' // 导入合同API

  // 定义props
  const props = defineProps({
    contractId: {
      type: String,
      default: '',
    },
  })

  // 图片预览相关
  const imagePreviewVisible = ref(false)
  const previewImage = ref({
    url: '',
    title: '',
  })

  // 文档预览相关
  const documentPreviewVisible = ref(false)
  const previewDocument = ref({
    url: '',
    title: '',
    type: '', // 'pdf' 或 'office'
  })
  // 是否显示备用预览选项
  const hasBackupPreviewOptions = ref(false)
  // 是否全屏显示
  const isFullscreen = ref(false)

  // 切换全屏模式
  const toggleFullscreen = () => {
    isFullscreen.value = !isFullscreen.value
  }

  // 监听窗口大小变化，调整预览窗口大小
  onMounted(() => {
    window.addEventListener('resize', handleResize)
  })

  // 在组件销毁时移除事件监听器和清除定时器
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    // 清除防抖定时器
    if (contractIdUpdateTimer) {
      clearTimeout(contractIdUpdateTimer)
      contractIdUpdateTimer = null
    }
  })

  // 处理窗口大小变化
  const handleResize = () => {
    if (documentPreviewVisible.value) {
      // 可以在这里添加额外的调整逻辑
    }
  }

  // 路由
  const router = useRouter()
  const route = useRoute()

  // 激活的Tab
  const activeTab = ref('basic')

  // 加载状态
  const loading = ref(false)

  // 合同详情
  const contractDetail = ref({
    id: '',
    name: '',
    code: '',
    subject_title: '',
    cate_title: '',
    customer: '',
    contact_name: '',
    contact_address: '',
    contact_mobile: '',
    cost: 0,
    cost2: 0,
    cost3: 0,
    start_time: '',
    end_time: '',
    interval_time: '',
    delay: 0,
    sign_name: '',
    sign_department: '',
    sign_time: '',
    check_status: 0,
    archive_status: 0,
    stop_status: 0,
    void_status: 0,
    create_time: '',
    update_time: '',
    // 补充可能缺失的字段
    sign_uid: 0,
    admin_id: 0,
    admin_name: '',
    remark: '',
    subject_id: 0,
    cate_id: 0,
    did: 0,
    keeper_uid: 0,
    keeper_name: '',
    prepared_uid: 0,
    prepared_name: '',
    share_ids: '',
    file_ids: '',
    amount: 0,
    content: '',
    archive_time: '',
    stop_time: '',
    void_time: '',
    delete_time: 0,
    attachments: [] as any[],
  })

  // 操作日志
  const logs = ref([])

  // 返回上一页
  const goBack = () => {
    router.back()
  }

  // 编辑合同
  const handleEdit = () => {
    router.push(`/contract/contract/edit/${contractDetail.value.id}`)
  }

  // 从合同创建案件
  const handleCreateCase = async () => {
    try {
      // 调用后端接口创建案件
      const request = (await import('@/utils/request')).default
      const res = await request({
        url: '/api/contract/contract/create_case_from_contract',
        method: 'post',
        data: {
          contract_id: contractDetail.value.id,
        },
      })

      if (res.data.code === 0) {
        ElMessage.success('案件创建成功')
        // 跳转到案件详情页面
        router.push(`/lawcase/case/view/${res.data.id}`)
      } else {
        ElMessage.error(res.data.msg || '案件创建失败')
      }
    } catch (error) {
      ElMessage.error('案件创建失败')
    }
  }

  // 判断是否为图片文件
  const isImageFile = (ext: string): boolean => {
    if (!ext) return false
    const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
    return imageExts.includes(ext.toLowerCase())
  }

  // 判断是否为PDF文件
  const isPdfFile = (ext: string): boolean => {
    if (!ext) return false
    return ext.toLowerCase() === 'pdf'
  }

  // 判断是否为Office文档
  const isOfficeFile = (ext: string): boolean => {
    if (!ext) return false
    const officeExts = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']
    return officeExts.includes(ext.toLowerCase())
  }

  // 判断文件是否可以预览
  const isPreviewableFile = (ext: string): boolean => {
    return isImageFile(ext) || isPdfFile(ext) || isOfficeFile(ext)
  }

  // 预览文件
  const previewFile = (file: any) => {
    if (!file || !file.filepath) {
      ElMessage.warning('文件链接不存在')
      return
    }

    // 重置全屏状态
    isFullscreen.value = false

    try {
      // 处理文件路径，确保使用正确的URL格式
      let fileUrl = file.filepath
      // 处理路径中的反斜杠
      fileUrl = fileUrl.replace(/\\/g, '/')
      // 确保路径是完整的URL
      if (!fileUrl.startsWith('http://') && !fileUrl.startsWith('https://')) {
        fileUrl = apiBaseUrl.value + fileUrl
      }

      // 根据文件类型选择不同的预览方式
      const fileExt = file.fileext ? file.fileext.toLowerCase() : ''

      if (isImageFile(fileExt)) {
        // 图片预览 - 使用已有的预览对话框
        previewImage.value = {
          url: fileUrl,
          title: file.name || '图片预览',
        }
        imagePreviewVisible.value = true
      } else if (isPdfFile(fileExt)) {
        // PDF预览
        previewDocument.value = {
          url: fileUrl,
          title: file.name || 'PDF预览',
          type: 'pdf',
        }
        documentPreviewVisible.value = true
      } else if (isOfficeFile(fileExt)) {
        // Office文档预览 - 使用Google Docs Viewer（更稳定的替代方案）
        // 因为Office Online服务可能无法访问内部文件，使用Google Docs Viewer作为替代
        const encodedUrl = encodeURIComponent(fileUrl)

        // 使用Google Docs Viewer预览
        const googleDocsUrl = `https://docs.google.com/viewer?url=${encodedUrl}&embedded=true`

        previewDocument.value = {
          url: googleDocsUrl,
          title: file.name || '文档预览',
          type: 'office',
        }
        documentPreviewVisible.value = true

        // 添加备用选项
        hasBackupPreviewOptions.value = true
      } else {
        // 其他类型文件，提示下载后查看
        ElMessage.info('此类型文件不支持在线预览，请下载后查看')
      }
    } catch (error) {
      ElMessage.error('文件预览失败')
    }
  }

  // 格式化货币（不带符号）
  const formatCurrencyWithoutSymbol = (value: number | string): string => {
    if (value === null || value === undefined || value === '') {
      return '0.00'
    }

    const num = typeof value === 'string' ? parseFloat(value) : value
    if (isNaN(num)) {
      return '0.00'
    }

    return num.toLocaleString('zh-CN', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    })
  }

  // 格式化文件大小
  const formatFileSize = (size: number | string): string => {
    if (!size || size === 0) return '0 B'

    const num = typeof size === 'string' ? parseInt(size) : size
    if (isNaN(num) || num <= 0) return '0 B'

    const units = ['B', 'KB', 'MB', 'GB', 'TB']
    let i = 0
    let fileSize = num

    while (fileSize >= 1024 && i < units.length - 1) {
      fileSize /= 1024
      i++
    }

    return Math.round(fileSize * 100) / 100 + ' ' + units[i]
  }

  // 下载文件
  const downloadFile = (file: any) => {
    if (!file || !file.filepath) {
      ElMessage.warning('文件链接不存在')
      return
    }

    try {
      // 处理文件路径，确保使用正确的URL格式
      let fileUrl = file.filepath
      // 处理路径中的反斜杠
      fileUrl = fileUrl.replace(/\\/g, '/')
      // 确保路径是完整的URL
      if (!fileUrl.startsWith('http://') && !fileUrl.startsWith('https://')) {
        fileUrl = apiBaseUrl.value + fileUrl
      }
      // 创建隐藏的a标签进行下载
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = fileUrl
      link.setAttribute('download', file.name || 'download')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      ElMessage.success('文件下载已开始')
    } catch (error) {
      ElMessage.error('文件下载失败')
    }
  }

  // 计算合同期限（剩余天数）
  const calculateDaysLeft = (endTime: number | string): number => {
    if (!endTime) {
      return 0
    }

    const end = typeof endTime === 'string' ? parseInt(endTime) : endTime

    if (isNaN(end) || end <= 0) {
      return 0
    }

    // 获取当前时间戳（秒级）
    const now = Math.floor(Date.now() / 1000)

    // 计算剩余天数
    const diffTime = end - now
    const diffDays = Math.ceil(diffTime / (24 * 60 * 60))

    return diffDays
  }

  // 获取合同详情
  const getContractDetail = async (id: string) => {
    if (!id || id === '') {
      console.warn('合同ID为空，无法获取合同详情')
      return
    }

    try {
      loading.value = true

      // 使用标准 API 调用方式
      const response: any = await contractApi.viewContract({ id })

      // 检查响应是否有效
      if (!response) {
        console.error('获取合同详情失败：响应为空')
        ElMessage.error('获取合同详情失败：服务器无响应')
        return
      }

      // 处理可能的不同响应格式
      if (response && response.code === 0 && response.data) {
        // 正常的响应格式
        contractDetail.value = { ...contractDetail.value, ...response.data }
      } else if (response && response.data && response.res.data.code === 0 && response.res.data) {
        // 可能的嵌套响应格式
        contractDetail.value = { ...contractDetail.value, ...response.res.data }
      } else {
        // 收到响应但数据不符合预期
        console.error('响应格式不符合预期:', response)
        let errorMsg = '获取合同详情失败，响应格式不符合预期'
        if (response && response.msg) {
          errorMsg += '：' + response.msg
        }
        ElMessage.error(errorMsg)
      }
    } catch (error: any) {
      console.error('获取合同详情出错:', error)
      let errorMessage = '获取合同详情失败'

      if (error) {
        if (error.message) {
          errorMessage += ': ' + error.message
        } else if (error.response && error.response.data && error.response.res.data.msg) {
          errorMessage += ': ' + error.response.res.data.msg
        }
      }

      ElMessage.error(errorMessage)
    } finally {
      loading.value = false
    }
  }

  // 获取操作日志
  const getLogs = async (contractId: string) => {
    try {
      // 暂时注释掉日志获取逻辑，因为后端没有提供相关接口
      // const response = await axios.get(`/contract/contract/log_view`, {
      //   params: { contract_id: contractId }
      // })
      //
      // if (response.res.data.code === 0) {
      //   logs.value = response.res.data
      // } else {
      //   ElMessage.error(response.res.data.msg || '获取操作日志失败')
      // }

      // 暂时设置为空数组
      logs.value = []
    } catch (error) {
      ElMessage.error('获取操作日志失败')
    }
  }

  // 刷新数据
  const refreshData = () => {
    const contractId = route.params.id as string
    if (contractId) {
      getContractDetail(contractId)
      getLogs(contractId)
    } else {
      ElMessage.warning('未找到合同ID')
    }
  }

  // 初始化数据
  onMounted(() => {
    loadContractData()
  })

  // 监听 contractId 变化
  // 使用防抖避免短时间内多次触发
  let contractIdUpdateTimer: number | null = null
  watch(
    () => props.contractId,
    newVal => {
      if (newVal) {
        // 清除之前的定时器
        if (contractIdUpdateTimer) {
          clearTimeout(contractIdUpdateTimer)
        }

        // 使用定时器防抖，100ms内多次变化只会执行一次
        contractIdUpdateTimer = window.setTimeout(() => {
          // 避免重复调用，检查是否与当前已加载的ID相同
          if (contractDetail.value.id !== newVal) {
            getContractDetail(newVal)
            getLogs(newVal)
          }
        }, 100)
      }
    }
  )

  // 监听文档预览对话框的关闭
  watch(documentPreviewVisible, newVal => {
    // 当对话框关闭时，重置全屏状态
    if (!newVal) {
      isFullscreen.value = false
    }
  })

  // 加载合同数据
  const loadContractData = () => {
    let contractId = ''
    if (props.contractId) {
      contractId = props.contractId
    } else {
      contractId = route.params.id as string
    }

    // 只有当contractId不为空且与当前已加载的ID不同时才加载数据
    if (contractId && contractDetail.value.id !== contractId) {
      getContractDetail(contractId)
      getLogs(contractId)
    }
  }

  // 在新标签页中打开文档
  const openInNewTab = (url: string) => {
    window.open(url, '_blank')
  }

  // 使用Office Online预览服务
  const previewWithOfficeOnline = (fileUrl: string) => {
    const encodedUrl = encodeURIComponent(fileUrl)
    const officeOnlineUrl = `https://view.officeapps.live.com/op/embed.aspx?src=${encodedUrl}`

    previewDocument.value = {
      url: officeOnlineUrl,
      title: previewDocument.value.title,
      type: 'office',
    }
  }

  // 使用Google Docs预览服务
  const previewWithGoogleDocs = (fileUrl: string) => {
    const encodedUrl = encodeURIComponent(fileUrl)
    const googleDocsUrl = `https://docs.google.com/viewer?url=${encodedUrl}&embedded=true`

    previewDocument.value = {
      url: googleDocsUrl,
      title: previewDocument.value.title,
      type: 'office',
    }
  }

  // 直接下载文件
  const directDownload = (file: any) => {
    documentPreviewVisible.value = false
    downloadFile(file)
  }

  // API 基础 URL
  const apiBaseUrl = ref(import.meta.env.VITE_API_BASE_URL || '')
</script>

<style scoped>
  .sale-contract-view {
    padding: 20px;
    min-height: calc(100vh - 140px);
  }

  .contract-detail-card {
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05) !important;
    border-radius: 8px !important;
    margin-bottom: 20px;
  }

  .contract-detail-content {
    padding: 0 10px;
  }

  .info-section {
    margin-bottom: 30px;
    position: relative;
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 8px;
  }

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0;
  }

  .contract-category-tag {
    background-color: #ecf5ff;
    color: #409eff;
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 14px;
    font-weight: 500;
    text-align: right;
  }

  .info-descriptions {
    background-color: #fafafa;
    border-radius: 6px;
    padding: 10px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 5px;
  }

  .customer-detail-tabs {
    margin-top: 20px;
  }

  .tab-content {
    padding: 20px 0;
  }

  .tab-toolbar {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;
  }

  .text-ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
    width: 100%;
  }

  .drawer-content {
    height: calc(100% - 70px); /* 减去底部按钮区域的高度 */
    overflow-y: auto;
    padding: 10px 20px;
  }

  .drawer-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 16px 20px;
    border-top: 1px solid #ebeef5;
    gap: 12px;
  }

  /* 自定义表格样式 */
  .custom-table {
    --el-table-border-color: #ebeef5;
    --el-table-header-bg-color: #f5f7fa;
    --el-table-row-hover-bg-color: #f5f7fa;
    border-radius: 6px;
    overflow: hidden;
  }

  /* 更轻量的描述列表样式 */
  :deep(.el-descriptions__cell) {
    padding: 12px !important;
  }

  :deep(.el-descriptions__label) {
    width: 120px;
    font-weight: 500;
    color: #606266;
  }

  :deep(.el-descriptions__content) {
    word-break: break-all;
    color: #303133;
  }

  /* 标签样式优化 */
  :deep(.el-tag) {
    border-radius: 4px;
    padding: 0 8px;
    height: 24px;
    line-height: 24px;
  }

  /* 联系人列表样式 */
  .contact-name-cell {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .avatar-icon {
    background-color: #e6f0fc;
    color: #409eff;
  }

  .default-tag {
    margin-left: auto;
    padding: 0 6px;
    font-size: 12px;
  }

  /* 附件列表样式 */
  .attachment-list {
    width: 100%;
    overflow: visible;
    margin-bottom: 20px;
  }

  .attachment-list .el-table {
    width: 100%;
  }

  /* 确保表格显示所有行 */
  .attachment-list .el-table__body-wrapper {
    overflow: visible;
  }

  /* 空数据提示 */
  .empty-data {
    padding: 40px 0;
    text-align: center;
  }

  /* 添加响应式样式 */
  @media (max-width: 768px) {
    .sale-contract-view {
      padding: 10px;
    }

    .el-descriptions {
      width: 100%;
      overflow-x: auto;
    }

    .tab-toolbar {
      flex-direction: column;
      align-items: flex-start;
    }

    .tab-toolbar .el-button {
      margin-bottom: 10px;
    }

    .section-header {
      flex-direction: column;
      align-items: flex-start;
    }

    .contract-category-tag {
      margin-top: 10px;
      align-self: flex-end;
    }
  }

  /* 图片预览对话框样式 */
  .image-preview-dialog {
    margin-top: 50px;
  }

  .image-preview-dialog .el-dialog__body {
    padding: 0;
  }

  .image-preview-container {
    text-align: center;
    background-color: #f5f5f5;
    min-height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .preview-image {
    max-width: 100%;
    max-height: 70vh;
  }

  /* 文档预览对话框样式 */
  .document-preview-dialog {
    margin-top: 10px;
    max-height: 100vh;
  }

  .document-preview-dialog :deep(.el-dialog__header) {
    padding: 12px 20px;
    margin-right: 0;
    background-color: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;
  }

  .document-preview-dialog :deep(.el-dialog__title) {
    font-size: 16px;
    font-weight: 600;
  }

  .document-preview-dialog :deep(.el-dialog__body) {
    padding: 0;
    height: calc(95vh - 120px);
    overflow: hidden;
  }

  .document-preview-dialog :deep(.el-dialog__close) {
    font-size: 18px;
  }

  .document-preview-toolbar {
    padding: 8px 15px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .toolbar-left,
  .toolbar-right {
    display: flex;
    gap: 10px;
    align-items: center;
  }

  .document-preview-container {
    height: calc(100% - 42px);
    background-color: #f5f5f5;
    overflow: hidden;
    position: relative;
  }

  .document-preview-container::before {
    content: '正在加载文档预览...';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #909399;
    z-index: 0;
  }

  .document-preview-iframe {
    width: 100%;
    height: 100%;
    border: none;
    position: relative;
    z-index: 1;
    background-color: #fff;
  }

  .pdf-preview {
    background-color: #525659;
  }

  /* 全屏模式下的样式调整 */
  .document-preview-dialog.is-fullscreen :deep(.el-dialog__body) {
    height: calc(100vh - 60px);
  }

  .document-preview-dialog.is-fullscreen .document-preview-container {
    height: calc(100% - 42px);
  }

  .document-preview-dialog.is-fullscreen .document-preview-toolbar {
    padding: 6px 15px;
  }

  .document-preview-dialog.is-fullscreen .document-preview-iframe {
    height: 100%;
    background-color: #fff;
  }

  /* 添加加载指示样式 */
  .document-preview-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    z-index: 0;
    color: #909399;
  }

  .document-preview-loading .el-icon {
    font-size: 2rem;
    margin-bottom: 10px;
  }

  /* 加载中样式 */
  .loading-placeholder {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
    color: #909399;
  }

  /* 数据错误提示 */
  .data-error-tip {
    padding: 20px;
    text-align: center;
    color: #f56c6c;
    background-color: #fef0f0;
    border-radius: 4px;
    margin: 20px 0;
  }

  /* 调试区域 */
  .debug-area {
    margin-top: 20px;
    padding: 10px;
    background-color: #f8f9fa;
    border: 1px dashed #ccc;
  }

  .debug-area pre {
    background-color: #f1f1f1;
    padding: 10px;
    border-radius: 4px;
    overflow-x: auto;
  }
</style>
